package com.tdam2011.grupo05.processor;

import java.io.UnsupportedEncodingException;

import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.tdam2011.grupo05.services.constant.ServiceActions;
import com.tdam2011.grupo05.utils.parser.XMLParser;
import com.tdam2011.grupo05.utils.parser.XMLParser.Entry;

@SuppressWarnings("unused")
public class RegisterUserProcessor implements Processor {

	private static final String TAG = "RegisterUserProcessor";
	public static final String ERROR = "error_result";
	public static final String ERROR_ID = "error_id_result";
	public static final String HAVE_ERROR = "have_error_result";

	private final Context mContext;
	private int mId;
	private String mUser;
	private String mPass;
	private LocalBroadcastManager mLocalBroadcastManager;

	public RegisterUserProcessor(Context context) {
		mContext = context;
		mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
	}

	public void setData(int id, String user, String pass) {
		mId = id;
		mUser = user;
		mPass = pass;
	}

	@Override
	public StringEntity handleRequest() throws UnsupportedEncodingException {
		Log.d(TAG, "handleRequest");
		StringEntity se = new StringEntity("<action id=\"" + mId
				+ "\" name=\"register-user\">" + "<action-detail>"
				+ "<user username=\"" + mUser + "\" password=\"" + mPass
				+ "\"/>" + "</action-detail></action>", HTTP.UTF_8);
		se.setContentType("text/xml");

		return se;
	}

	@Override
	public void handleResponse(Entry response, String requestAction) {
		Log.d(TAG, "handleResponse");
		Bundle data = new Bundle();
		data.putBoolean(HAVE_ERROR, true);
		Intent intent = new Intent(ServiceActions.REGISTER_USER_ACTION);

		if (response == null) {
			data.putString(ERROR, "no connection");
			data.putInt(ERROR_ID, 0);

		} else if (response.getType().equals(XMLParser.ERROR_RESULT)) {
			String detail = response.getDetail();
			data.putString(ERROR, response.getType());
			data.putInt(ERROR_ID, response.getCode());

		} else if (response.getType().equals(XMLParser.SUCCESS_RESULT)) {
			data.putBoolean(HAVE_ERROR, false);
		}
		intent.putExtras(data);
		mLocalBroadcastManager.sendBroadcast(intent);
	}

	@Override
	public void cancelRequest() {

	}
}
